<?php

namespace app\common\model;

use org\util\TreeUtil;
use think\Request;
use think\Validate;
class UserModel extends BaseModel
{
    protected $name = 'user'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改
    //类型自动转换
    protected $type = [];

    /*读取器*/

    /*修改器*/
    protected function setPasswordAttr($value)
    {
        return md5($value);
    }

    public function getUserInfo($uid)
    {
        $info=$this->where('uid',$uid)->find()->toArray();
        $memberInfo=UserMemberModel::get($uid)->toArray();
        return array_merge($info,$memberInfo);
    }
    /**
     * 添加用户
     * @param $data
     * @return bool
     */
    public function addData($data)
    {
        if (empty($data['username']) && empty($data['mobile']) && empty($data['email'])) {
            $this->error = '用户名/手机号/邮箱至少应该填写一个';
            return false;
        }
        if (!empty($data['username'])) {
            if ($this->isUserName($data['username']) === false) {
                return false;
            }
            if ($this->where('username', $data['username'])->find()) {
                $this->error = '该用户已存在！';
                return false;
            }
        }
        if (!empty($data['mobile'])) {
            if ($this->isMobile($data['mobile']) === false) {
                return false;
            }
            if ($this->where('mobile', $data['mobile'])->find()) {
                $this->error = '该手机号已注册！';
                return false;
            }
        }
        if (!empty($data['email'])) {
            if($this->isEmail($data['email'])===false){
                return false;
            }
            if ($this->where('email', $data['email'])->find()) {
                $this->error = '该邮箱已注册！';
                return false;
            }
        }
        if (empty($data['birthday'])) {
            $data['birthday'] = null;
        }
        $this->isUpdate(false)->allowField(true)->save($data);
        $uid = $this->getData('uid');
        if($data['site_id']>=0){
            $memberModel = new UserMemberModel();
            $data['uid'] = $uid;
            $memberModel->addData($data);
        }
        return true;
    }

    /**
     * 编辑用户
     * @param $data
     * @return bool
     */
    public function editData($data)
    {
        if (empty($data['password'])) {
            unset($data['password']);
        }
        $info = $this->get($data['uid']);
        if (!empty($data['username'])) {
            if ($info['username'] != $data['username']) {
                if ($this->isUserName($data['username']) === false) {
                    return false;
                }
                if ($this->where('username', $data['username'])->find()) {
                    $this->error = '该用户已存在！';
                    return false;
                }
            }
        }
        if (!empty($data['mobile'])) {
            if ($info['mobile'] != $data['mobile']) {
                if ($this->isMobile($data['mobile']) === false) {
                    return false;
                }
                if ($this->where('mobile', $data['mobile'])->find()) {
                    $this->error = '该手机号已注册！';
                    return false;
                }
            }
        }
        if (!empty($data['email'])) {
            if ($info['email'] != $data['email']) {
                if ($this->isEmail($data['email']) === false) {
                    return false;
                }
                if ($this->where('email', $data['email'])->find()) {
                    $this->error = '该邮箱已注册！';
                    return false;
                }
            }
        }
        if ($info['uid'] == 1) $data['status'] = 1; //系统管理员不允许禁用
        if (empty($data['birthday'])) {
            $data['birthday'] = null;
        }
        $this->isUpdate(true)->allowField(true)->save($data);
        $uid = $this->getData('uid');
        if($data['site_id']>=0){
            $memberModel = new UserMemberModel();
            $data['uid'] = $uid;
            $memberModel->editData($data);
        }
        return true;
    }

    /**
     * 禁用用户
     * @param $uid
     * @return bool
     */
    public function setStatus($uid)
    {
        if ($uid == 1) {
            $this->error = '系统管理员不允许禁用';
            return false;
        }
        $status = $this->where('uid',$uid)->value('status');
        $status = $status==1?0:1;
        $this->where('uid',$uid)->setField('status',$status);
        return true;
    }


    /**
     * 会员登录
     * @param $account
     * @param $password
     * @param string $utype
     * @return bool|string
     */
    public function checkMemberLogin($account = '', $password = '')
    {
        if (empty($account) || empty($password)) {
            $request = Request::instance();
            $account = $request->param('account');
            $password = $request->param('password');
        }
        $validate = new Validate(['account' => 'require', 'password' => 'require']);
        $data = ['account' => $account, 'password' => $password];
        if (!$validate->check($data)) {
            $this->error = $validate->getError();
            return false;
        }
        $field = $this->checkUserName($account);
        if (empty($field)) {
            $this->error = '帐户信息有误！';
            return false;
        }
        $user = $this->where($field, $account)->where('site_id','>=',0)->find();
        if (empty($user)) {
            $this->error = '用户不存在！';
            return false;
        }
        if ($user->getData('password') == md5($password)) {
            $status = $user->getData('status');
            $uid = $user->getData('uid');
            $siteId = $user->getData('site_id');
            if ($status == 1) {
                $loginData = [
                    'last_login_time' => time(),
                    'last_login_ip' => get_client_ip(),
                    'login_times' => $user->getData('login_times') + 1,
                ];
                $this->where('uid', $uid)->update($loginData);
                $token = config('base.login_token');
                $des = str_encode($uid . $token . $siteId);
                return $des;
            }
            $this->error = '该用户已锁定';
            return false;
        }
        $this->error = '密码输入错误！';
        return false;
    }

    /**
     * 检测用户登录
     * @param $account
     * @param $password
     * @return bool
     */
    public function checkSysLogin($account, $password)
    {
        $field = $this->checkUserName($account);
        if (empty($field)) {
            $this->error = '帐户信息有误！';
            return false;
        }
        $user = $this->where($field, $account)->where('site_id',-1)->find();
        if (empty($user)) {
            $this->error = '用户不存在！';
            return false;
        }
        if ($user->getData('password') == md5($password)) {
            $status = $user->getData('status');
            $uid = $user->getData('uid');
            $siteId = $user->getData('site_id');
            if ($status == 1) {
                $groupId = $user->getData('group_id');   //获取权限信息
                if ($groupId == 0 && $siteId > 0) {
                    $this->error = '该用户还未授权！';
                    return false;
                }
                $loginData = [
                    'last_login_time' => time(),
                    'last_login_ip' => get_client_ip(),
                    'login_times' => $user->getData('login_times') + 1,
                ];
                $this->where('uid', $uid)->update($loginData);
                $token = config('base.login_token');
                $des = str_encode($uid . $token . $siteId);
                return $des;
            }
            $this->error = '该用户已锁定';
            return false;
        }
        $this->error = '密码输入错误！';
        return false;
    }

    /**
     * 获取用户权限
     * @param $uid
     * @param $utype
     * @return array
     */
    public function getMyRuleList($groupId, $utype)
    {
        $ruleList = cache('auth_rule_' . $utype);
        if (empty($ruleList)) {
            $model = new AuthRuleModel();
            $model->updateCache($utype);
            $ruleList = cache('auth_rule_' . $utype);
        }
        $authGroupModel = new AuthGroupModel();
        $rules = $authGroupModel->where('group_id', $groupId)->where('status', 1)->value('rules');
        if (empty($rules)) {
            return [];
        }
        if ($rules != 'all') {
            foreach ($ruleList as $k => $v) {
                if (in_array($k, explode(',', $rules))) {
                    $myRuleList[$k] = $v;
                }
            }
        } else {
            $myRuleList = $ruleList;
        }
        $treeRule = TreeUtil::channelLevel($myRuleList, 0, "&nbsp;", 'rule_id', 'rule_pid');
        return $treeRule;
    }

    /**
     * 获取用户投稿CMS栏目
     */
    public function getCmsCategory($groupId)
    {
        $category = cache('cms_category');
        $authGroupModel = new AuthGroupModel();
        $cmsCids = $authGroupModel->where('group_id', $groupId)->where('status', 1)->value('cms_cids');
        if (empty($cmsCids)) {
            return [];
        }
        if ($cmsCids != 'all') {
            foreach ($category as $k => $v) {
                if (in_array($k, explode(',', $cmsCids))) {
                    $result[$k] = $v;
                }
            }
        } else {
            $result = $category;
        }
        return $result;
    }

    /**
     * 获取用户投稿商品栏目
     */
    public function getGoodsCategory($groupId)
    {
        $category = cache('goods_category');
        $authGroupModel = new AuthGroupModel();
        $goodsCids = $authGroupModel->where('group_id', $groupId)->where('status', 1)->value('goods_cids');
        if (empty($goodsCids)) {
            return [];
        }
        if ($goodsCids != 'all') {
            foreach ($category as $k => $v) {
                if (in_array($k, explode(',', $goodsCids))) {
                    $result[$k] = $v;
                }
            }
        } else {
            $result = $category;
        }
        return $result;
    }

    /**
     * @param $account
     * 检测用户名
     */
    public function checkUserName($account)
    {
        if ($this->isUserName($account)) {
            return 'username';
        }
        if ($this->isMobile($account)) {
            return 'mobile';
        }
        if ($this->isEmail($account)) {
            return 'email';
        }
        return '';
    }

    /**
     * 是否用户名
     * @param $username
     * @return bool
     */
    public function isUserName($username)
    {
        $valid = Validate::regex($username, '/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){3,19}$/');
        if ($valid) {
            return true;
        } else {
            $this->error = '用户名只能为字母和数字且必须以字母开头';
            return false;
        }
    }

    /**
     * 是否手机号
     */
    public function isMobile($mobile)
    {
        $valid = Validate::regex($mobile, '/^1[3456789]{1}\d{9}$/');
        if ($valid) {
            return true;
        } else {
            $this->error = '手机号格式不正确';
            return false;
        }
    }

    /**
     * 是否邮箱
     */
    public function isEmail($email)
    {
        $valid = Validate::is($email, 'email');
        if ($valid) {
            return true;
        } else {
            $this->error = '手机号格式不正确';
            return false;
        }
    }
}